<?php

namespace App\Http\Controllers\API;

use App\Models\Bonus;
use App\Models\Role;
use App\Models\Wechat;
use App\Repositories\BonusRepository;
use App\Repositories\UsersRepository;
use App\Repositories\WechatRepository;
use App\User;
use App\ZL\Controllers\ApiBaseController;
use App\ZL\Library\Curl;
use App\ZL\Library\ErrorCode;
use App\ZL\ORG\Xcx\Common;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserCenterController extends ApiBaseController
{
    protected $xcx;
    protected $shop_id=0;
    protected $user;

    protected $appid;
    protected $secret;
    protected $bonus_repostory;
    protected $wechatRepository;

    public function __construct(UsersRepository $usersRepository, BonusRepository $bonusRepository, WechatRepository $wechatRepository)
    {
//        $this->appid = config('easywechat.app_id');
//        $this->secret = config('easywechat.secret');
        $shop_id = \request('shop_id');
        if($shop_id){
            $this->shop_id = $shop_id;
            $wechat = Wechat::where('shop_id',$shop_id)->first();
            if($wechat){
                $this->appid = $wechat->app_id;
                $this->secret = $wechat->secret;
            }
        }

        $this->user = $usersRepository;
        $this->bonus_repostory = $bonusRepository;
        $this->wechatRepository = $wechatRepository;
        $this->xcx = new Common($this->appid,$this->secret);
    }

//    public function getSessionKey()
//    {
//        return isset($_SERVER['HTTP_AUTHTOKEN'])?$_SERVER['HTTP_AUTHTOKEN']:I('authToken');
//    }
    public function test()
    {
//        $app = new Application(config('easywechat'));
//        $userService = $app->user;
//        $user = $userService->get("oryQC0ZxNCdtKX_n6HFlb3Oma96c");
//        dd($user);
        $users = User::whereNotNull('openid')->get();
        $app = new Application(config('wechat'));
        $userService = $app->user;
        foreach ($users as $v) {
            dump($v->id);
            try {
                $user = $userService->get($v->openid);

                $data = [
                    'nickname' => $user->nickname,
                    'avatar_url' => $user->headimgurl,
                    'sex' => $user->sex,
                    'unionid' => $user->unionid,
                    'city' => $user->city,
                    'session_id' => null,
                ];
                $v->update($data);
            } catch (\EasyWeChat\Core\Exceptions\HttpException $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }
//            if(!empty($user)){
//                if(isset($user['nickname'])){
//                    echo $user['nickname'];
//                    echo '<br/>';
//                    $data = [
//                        'nickname'=>$user['nickname'],
//                        'avatar_url'=>$user['headimgurl'],
//                        'sex'=>$user['sex'],
//                        'unionid'=>$user['unionid'],
//                        'city'=>$user['city'],
//                        'session_id'=>null,
//                    ];
//                    $v->update($data);
//                }else{
//                    dump($user);
//                }
//            }
//        }
//        $access_token = $this->xcx->getAccessToken();
//        dump($access_token);
//        $url = 'https://api.weixin.qq.com/cgi-bin/user/info';
//        $data = [
//            'access_token'=>$access_token,
//            'openid'=>'oryQC0ZIF96tGK2_23yKp4VKC0ZQ',
//            'lang'=>'zh_CN',
//        ];
//        $res = Curl::post($url,$data);
//        dd($res);
    }

    public function phoneLogin(Request $request)
    {
        $phone = $request->phone;
        $password = $request->password;
        if(!$phone || !$password){
            return responseZK(0, null, '缺少参数');
        }
        $user = User::where('phone', $phone)->first();
        if(!$user)
            return responseZK(0, null, '找不到用户');
        if(Hash::check($password, $user->password)){
            $session_id = Str::random(40);
            $user->session_id = $session_id;
            $user->save();
            $res['id'] = $user->id;
            $res['session_id'] = $session_id;
            $data = ['id' => $user->id, 'remember_token' => $user->remember_token];
            cache([$session_id => json_encode($data)], 1440);
            return responseZK(1, $res, '登录成功');
        }else{
            return responseZK(0, null, '密码错误');
        }

    }

    public function getSessionKey(Request $request)
    {
        $data = json_decode($this->xcx->getSessionKey($request->code),true);
        $parent_id = request('parent_id', 0);
        return $this->handleUser($data,$parent_id);
    }

    public function handleUser($data,$parent_id)
    {
        $tmpFileStr = ROOT_PATH.'/lock.lock';
        $lockhandle = lock_thisfile($tmpFileStr,true);
        if($lockhandle) {
            if (isset($data['session_key'])) {

                $session_id = Str::random(40);
                $res = [
                    'session_id' => $session_id,
                    'openid' => $data['openid'],
                ];
                if(isset($data['unionid']))
                    $res['unionid'] = $data['unionid'];

                if(isset($data['unionid']))
                    $user = User::where('unionid', $data['unionid'])->where('shop_id', $this->shop_id)->first();
                else
                    $user = User::where('xcx_openid', $data['openid'])->where('shop_id', $this->shop_id)->first();

                if(!$user)
                    $user = User::where('xcx_openid', $data['openid'])->where('shop_id', $this->shop_id)->first();

                if (!$user) {
                    $req  = request()->all();
                    $req['data'] = $data;
                    $_json = json_encode($req, 256);

                    $new_data = [
                        'xcx_openid' => $data['openid'],
                        'json' => $_json,
                        'remember_token' => Str::random(40),
                    ];
                    if($this->shop_id)
                        $new_data['shop_id'] = $this->shop_id;

                    if(isset($data['unionid']))
                        $new_data['unionid'] = $data['unionid'];
                    $user = User::create($new_data);


                    $parent = User::find($parent_id);
                    if ($parent_id && $parent) {
                        //新用户送优惠券
                        $this->bonus_repostory->dispatch('新用户满减券', $user->id, $this->shop_id);
                        //老用户送优惠券
                        $this->bonus_repostory->dispatchRandom(['10元新用户立减券','3元爆品立减券','5元尊享优惠券','5元惊喜满减券','6元新品立减券'], $parent_id, $this->shop_id);

                        $user->parent_id = $parent_id;
                    }
                    $res['new'] = 1;
                }elseif ($user && !$user->xcx_openid){
                    $req  = request()->all();
                    $req['data'] = $data;
                    $_json = json_encode($req, 256);

                    $user->xcx_openid = $data['openid'];
                    $user->json = $_json;
                    $user->remember_token = Str::random(40);

                    $parent = User::find($parent_id);
                    if ($parent_id && $parent) {
                        //新用户送优惠券
                        $this->bonus_repostory->dispatch('新用户满减券', $user->id, $this->shop_id);
                        //老用户送优惠券
                        $this->bonus_repostory->dispatch('新用户满减券', $parent_id, $this->shop_id);

                        $user->parent_id = $parent_id;
                    }
                    $res['new'] = 1;
                } else {
                    $res['new'] = 0;
                }
                $user->session_id = $session_id;
                if(isset($data['unionid']))
                    $user->unionid = $data['unionid'];
                $user->save();
                $res['id'] = $user->id;
                $data = array_merge($data, ['id' => $user->id, 'remember_token' => $user->remember_token]);
                cache([$session_id => json_encode($data)], isset($data['expires_in']) ? $data['expires_in'] / 60 : 120);

                unlock_thisfile($lockhandle,$tmpFileStr);
                return responseZK(1, $res);
            } else {
                return responseZK(0, [], $data['errmsg']);
            }
        }else{
            usleep(100000);
            return $this->handleUser($data,$parent_id);
        }
    }

    public function setLogin(Request $request)
    {
        $session_key = getSessionData()['session_key'];
        $data = '';
        $errCode = $this->xcx->decryptData($request,$session_key, $data);
        if ($errCode == 0) {
            $user = json_decode($data,true);
            $id = $this->user->checkHasAndSaveInfo($user, $this->shop_id);
            if($id){
//                addSessionData(['id'=>$id,'remember_token'=>$session_key]);

//            $secret = $this->user->saveTokenAndGetSecret($id,$session_key);

                $user = User::find($id);
                return responseZK(1,$user->toArray());
            }else{
                return responseZK(ErrorCode::$modelSaveError['code'],[],ErrorCode::$modelSaveError['msg']);
            }

        } else {
            return responseZK($errCode,[],$this->xcx->codeToStr($errCode));
        }
    }

    public function setParentId(Request $request)
    {
        $parent_id = $request->id;
        $user = Auth::user();
        if(!$user->parent_id){
            $parent = User::find($parent_id);
            if($parent){
                $has = User::where('parent_id', $user->id)->count();
                if($has==0){
                    $user->parent_id = $parent_id;
                    $user->save();
                }
            }
        }
        return responseZK(1,null,'ok');
    }

    public function getAccessToken()
    {
        $access_token = $this->xcx->getAccessToken();
        return responseZK(1,['token'=>$access_token]);
    }

    public function tempmsgServiceToUser()
    {
//        $this->xcx = new Common(config('xcx.appid'),config('xcx.secret'));
        $form_id = request('form_id',null);
        $content = request('content',null);
        $user_id = request('user_id',null);
        $user = User::find($user_id);
        if(!$user_id || !$content ||!$form_id){
            return responseZK(0,null,'缺少字段');
        }
        if(!$user){
            return responseZK(0,null,'找不到用户');
        }
        $options = [
            'app_id' => 'wxdfab6fc33d9b5230',
            'secret' => '6f5f75d9133e272bc8a1be583d7a5b02',
        ];
//        $accessToken = $this->xcx->getAccessToken();
        $app = new Application($options);
// 获取 access token 实例
        $accessToken = $app->access_token; // EasyWeChat\Core\AccessToken 实例
        $accessToken = $accessToken->getToken();
        $template_id = "SM_oPYu_XlrPoCExrq2_Be2nKGPAAQS5ANoS6V1xyAI";
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$accessToken;
        $_data = [
            'keyword1'=>[
                'value'=>date('Y-m-d H:i:s'),
                "color"=> "#173177"
            ],
            'keyword2'=>[
                'value'=>$content,
                "color"=> "#173177"
            ],
        ];
        //pages/chatAi/chatAi
        $data = [
            'template_id'=>$template_id,
            'touser'=>$user->xcx_openid,
            'page'=>"chat",
            'form_id'=>$form_id,
            'data'=>($_data),
        ];
        $res = request_post($url,json_encode($data));
//        $res = Curl::post($url,$data);
        $res = json_decode($res,256);
        if(isset($res['errcode']) && $res['errcode']==0){
            return responseZK(1);
        }else{
            return responseZK(0,null,$res['errmsg']);
        }
    }

    public function tempmsgUserToService()
    {
        $user_id = request('user_id');
        $content = request('content',null);

        if(!$user_id || !$content){
            return responseZK(0,null,'缺少字段');
        }

        $user = User::find($user_id);
        $templateId = 'kVv8ODBrEdesXqqi2wFZuki8AB-54wfvZSa6ns1_PYQ';
        $url = "https://mall.hellogreens.cn/web_index/index.html";
        $array = [
            'first'=>'亲爱的客服，您有新的消息',
            'keyword1'=>'用户:'.$user->nickname?$user->nickname:'无昵称'.' 留言',
            'keyword2'=>date('Y-m-d H:i:s'),
            'remark'=>$content,
        ];
        $role = Role::find(1);
        if($role->users->count()>0){
            foreach ($role->users as $_u) {
                $this->wechatRepository->sendTempMsg($_u->openid,$templateId,$url,$array);
            }
        }
        return responseZK(1);
    }

    public function sendTempMsg()
    {
        $user_id = request('user_id');
        $content = request('content',null);

        if(!$user_id || !$content){
            return responseZK(0,null,'缺少字段');
        }

        $user = User::find($user_id);
        if(!$user->openid)
            return responseZK(0,null,'用户没有openid');
        $templateId = 'kVv8ODBrEdesXqqi2wFZuki8AB-54wfvZSa6ns1_PYQ';
        $url = "https://mall.hellogreens.cn/web_index/index.html";
        $array = [
            'first'=>'亲爱的用户，您有新的客服回复消息',
            'keyword1'=>'客服回复',
            'keyword2'=>date('Y-m-d H:i:s'),
            'remark'=>$content,
        ];
        $this->wechatRepository->sendTempMsg($user->openid,$templateId,$url,$array);
        return responseZK(1);
    }
}
